<?php

/*
 * 两人开发，为不冲突而创建的临时文件
 * 开发完成后与Api.class.php 合并
 */

namespace Weixin;

use Weixin;

include_once('./Application/Weixin/Weixin.conf.php');

class Api2 {
    
    /**
     * 获取 微信 accesstoken
     */
    public function getAccessToken($app_id, $secret) {
        $url = sprintf(ACCESS_TOKEN_URL, $app_id, $secret);
        $token = file_get_contents(SESSION_DIR.'token');
        $token = json_decode($token,true);
        if (strlen($token['access_token']) > 1 && time() - $token['token_time'] < 3600) {
            
        } else {
            $re = $this->achieve($url);
            $token['access_token'] = $re['access_token'];
            $token['token_time'] = time();
            file_put_contents(SESSION_DIR.'token', json_encode($token));
        }
        return $token['access_token'];
    }

    public function createMenu($token, $id) {
        $url = sprintf(MENU_CREATE, $token);
        $re = $this->achieve($url, sprintf(WEIXIN_MENU, $id, $id));
        return $re;
    }

    /*
     * 微信授权
     */

    public function weixinAuth($id, $app_id, $type=false) {
        $callbackurl = "http://".MAIN_DOMAIN.$_SERVER['REQUEST_URI'];
        if($type){
            $url = OAUTH_URL_OAUTH;
        }else{
            $url = OAUTH_URL;
        }
        $url = sprintf($url, $app_id, urlencode($callbackurl));
        header('Location:' . $url);
        exit;
    }

    public function getUserToken($id, $app_id, $secret, $type = false) {
        if(file_exists(SESSION_DIR.session_id())){
            $_SESSION_ = json_decode(file_get_contents(SESSION_DIR.session_id()),true);
        }
        if (!$_SESSION_[$id]['open_id'] && !$_GET['code']) {
            $this->weixinAuth($id, $app_id, $type);
        }
        if (!$_SESSION_[$id]['open_id'] || strlen($_SESSION_[$id]['open_id']) < 1 || time()-$_SESSION_[$id]['user_access_token_time']>3600) {
            $url = sprintf(USER_TOKEN, $app_id, $secret, $_GET['code']);
            $re = $this->achieve($url);
            if($re['errcode'] == 40029){//微信报无效的code
                $this->weixinAuth($id, $app_id, $type);
            }
            $_SESSION_[$id]['user_access_token'] = $re['access_token'];
            $_SESSION_[$id]['user_access_token_time'] = time();
            $_SESSION_[$id]['open_id'] = $re['openid'];
            file_put_contents(SESSION_DIR.session_id(), json_encode($_SESSION_));
        }
        return;
    }
    
    public function getUserTokenAuth($id, $app_id, $secret, $type = false) {
        if(file_exists(SESSION_DIR.session_id())){
            $_SESSION_ = json_decode(file_get_contents(SESSION_DIR.session_id()),true);
        }
        if (!$_SESSION_[$id]['open_id'] && !$_GET['code']) {
            $this->weixinAuth($id, $app_id, $type);
        }
        if (!$_SESSION_[$id]['open_id'] || strlen($_SESSION_[$id]['open_id']) < 1 || time()-$_SESSION_[$id]['user_access_token_time']>3600) {
            $url = sprintf(USER_TOKEN, $app_id, $secret, $_GET['code']);
            $re = $this->achieve($url);
            if($re['errcode'] == 40029){//微信报无效的code
                $this->weixinAuth($id, $app_id, $type);
            }
            $_SESSION_[$id]['user_access_token'] = $re['access_token'];
            $_SESSION_[$id]['user_access_token_time'] = time();
            $_SESSION_[$id]['open_id'] = $re['openid'];
            file_put_contents(SESSION_DIR.session_id(), json_encode($_SESSION_));
        }
        return;
    }
    
    public function getSession(){
        return json_decode(file_get_contents(SESSION_DIR.session_id()),true);
    }

    public function createQrcode($app_id, $secret) {
        $data['action_name'] = 'QR_LIMIT_STR_SCENE';
        $data['action_info'] = array('scene' => array('scene_str' => '123'));
        $url = sprintf(WEIXIN_TICKET, $this->getAccessToken($app_id, $secret));
        $re = $this->achieve($url, json_encode($data));
        if (strlen($re['url']) > 1) {
            include_once(APP_PATH . "Weixin/phpqrcode/phpqrcode.php");
            $errorCorrectionLevel = "L"; // 纠错级别：L、M、Q、H  
            $matrixPointSize = "4"; // 点的大小：1到10  
            \QRcode::png($re['url'], false, $errorCorrectionLevel, $matrixPointSize);
            exit;
        }
        return false;
    }
    
    public function payMsgPush($open_id,$token,$order_number,$store_name,$subject,$price){
        $data = array('touser'=>$open_id,
                "template_id"=>WEINXIN_PAY_MSG_MODEL_ID,
            "url"=>'',
            "data"=>array(
                "keyword5"=>array('value'=>$store_name,"color"=>"#173177"),
                "keyword1"=>array('value'=>$subject,"color"=>"#173177"),
                "keyword2"=>array('value'=>$order_number,"color"=>"#173177"),
                "keyword3"=>array('value'=>$price,"color"=>"#173177"),
                "keyword4"=>array('value'=>date('Y-m-d H:i:s'),"color"=>"#173177"),
            )
                );
        return $this->msgPush(json_encode($data), $token);
    }
    
    private function msgPush($data,$token){
        return $this->achieve(sprintf(WEIXIN_MSG_PUSH,$token), $data);
    }
    
    public function getTicket($app_id, $secret){
        $ticket = file_get_contents(SESSION_DIR.'ticket');
        $ticket = json_decode($token,true);
        if (strlen($ticket['ticket']) > 1 && time() - $ticket['time'] < 3600) {
            
        } else {
            $token = $this->getAccessToken($app_id, $secret);
            $ticket = $this->achieve(sprintf(WEIXIN_TICKET_JS,$token));
            $ticket['ticket'] = $ticket['ticket'];
            $ticket['time'] = time();
            file_put_contents(SESSION_DIR.'ticket', json_encode($ticket));
        }
        return $ticket['ticket'];
    }
    
    public function getUserInfo($app_id, $secret){
        if(file_exists(SESSION_DIR.session_id())){
            $_SESSION_ = json_decode(file_get_contents(SESSION_DIR.session_id()),true);
        }

        $url = sprintf(WEIXIN_USER,$_SESSION_['system']['user_access_token'],$_SESSION_['system']['open_id']);
        return $this->achieve($url);
    }

    public function mediaGet($app_id,$secret,$pic){
          $token = $this->getAccessToken($app_id,$secret);
          $ss = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s';
          $url = sprintf($ss,$token,$pic);
          return $this->chieve($url);
    }
    
    function weixinShare(){
        $data['jsapi_ticket'] = $this->getTicket(WEIXIN_PAY_APP_ID, WEIXIN_PAY_SECRET);
        $data['noncestr'] = 'fewgasfgadussfeko'; //临时写死
        $data['timestamp'] = time();
        $data['url'] = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        ksort($data);
        foreach ($data as $k => $v) {
            $str .= $k . '=' . $v . '&';
        }
        $data['sign'] = sha1(substr($str, 0, -1));
        if (strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
            $data['weixin'] = true;
        }
        return $data;
    }

    public function chieve($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_NOBODY, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); 
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $tmpInfo = curl_exec($curl);
        $httpinfo = curl_getinfo($curl);
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        } 
        curl_close($curl);
        $tmpInfo = array_merge(array('header'=>$httpinfo),array('body'=>$tmpInfo)); 
        return $tmpInfo;
    }

    private function achieve($url, $data, $timeout = 30) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $tmpInfo = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);
        }
        curl_close($curl);
        return json_decode($tmpInfo, true);
    }

    public function foo($str) {
        $f = fopen('./public/upload/a.txt', 'a+');
        fwrite($f, $str . "\r\n");
        fclose($f);
    }

}
